<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>时间范围商品查询</title>
  
  <!-- Vuetify 3 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/@mdi/font@7.0.96/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/vuetify@3.4.0/dist/vuetify.min.css" rel="stylesheet">
  
  <!-- Vue 3 -->
  <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.js"></script>
  <!-- Vuetify 3 JS -->
  <script src="https://cdn.jsdelivr.net/npm/vuetify@3.4.0/dist/vuetify.min.js"></script>
</head>
<body>
  <div id="app">
    <v-app>
      <v-main>
        <v-container>
          <v-card class="mx-auto" max-width="800">
            <v-card-title class="text-h5">
              <v-icon start>mdi-calendar-range</v-icon>
              时间范围商品查询
            </v-card-title>
            
            <v-card-text>
              <v-form>
                <v-row>
                  <!-- 开始时间下拉框 -->
                  <v-col cols="12" md="4">
                    <v-select
                      v-model="startDate"
                      :items="availableMonths"
                      label="开始时间"
                      item-title="text"
                      item-value="value"
                      variant="outlined"
                      :loading="loadingStart"
                      :disabled="loadingStart"
                      @update:modelValue="onStartDateChange"
                      clearable
                    >
                      <template v-slot:item="{ props, item }">
                        <v-list-item v-bind="props">
                          <template v-slot:prepend>
                            <v-icon>mdi-calendar-start</v-icon>
                          </template>
                        </v-list-item>
                      </template>
                    </v-select>
                  </v-col>
                  
                  <!-- 结束时间下拉框 -->
                  <v-col cols="12" md="4">
                    <v-select
                      v-model="endDate"
                      :items="availableMonths"
                      label="结束时间"
                      item-title="text"
                      item-value="value"
                      variant="outlined"
                      :loading="loadingEnd"
                      :disabled="loadingEnd || !startDate"
                      :rules="[endDateRule]"
                      @update:modelValue="onEndDateChange"
                      clearable
                    >
                      <template v-slot:item="{ props, item }">
                        <v-list-item v-bind="props">
                          <template v-slot:prepend>
                            <v-icon>mdi-calendar-end</v-icon>
                          </template>
                        </v-list-item>
                      </template>
                    </v-select>
                  </v-col>
                  
                  <!-- 产品下拉框 -->
                  <v-col cols="12" md="4">
                    <v-select
                      v-model="selectedProduct"
                      :items="availableProducts"
                      label="选择产品"
                      item-title="name"
                      item-value="code"
                      variant="outlined"
                      :loading="loadingProducts"
                      :disabled="loadingProducts || !startDate || !endDate"
                      clearable
                      chips
                    >
                      <template v-slot:item="{ props, item }">
                        <v-list-item v-bind="props">
                          <template v-slot:title>
                            <span>{{ item.name }}</span>
                            <v-chip 
                              size="x-small" 
                              color="primary" 
                              class="ml-2"
                              v-if="item.category"
                            >
                              {{ item.category }}
                            </v-chip>
                          </template>
                          <template v-slot:subtitle>
                            <span>编码: {{ item.code }}</span>
                          </template>
                        </v-list-item>
                      </template>
                      
                      <template v-slot:selection="{ item }">
                        <v-chip>
                          <span>{{ item.raw.name }}</span>
                        </v-chip>
                      </template>
                    </v-select>
                  </v-col>
                </v-row>
                
                <!-- 操作按钮 -->
                <v-row>
                  <v-col cols="12">
                    <v-btn 
                      color="primary" 
                      @click="searchProducts"
                      :disabled="!startDate || !endDate || !selectedProduct"
                      :loading="searching"
                    >
                      <v-icon start>mdi-magnify</v-icon>
                      查询商品信息
                    </v-btn>
                    
                    <v-btn 
                      class="ml-2"
                      @click="resetSelections"
                      :disabled="!startDate && !endDate && !selectedProduct"
                    >
                      <v-icon start>mdi-refresh</v-icon>
                      重置
                    </v-btn>
                  </v-col>
                </v-row>
              </v-form>
            </v-card-text>
            
            <!-- 结果显示区域 -->
            <v-card-text v-if="searchResult">
              <v-divider class="my-4"></v-divider>
              <h3 class="text-h6 mb-4">查询结果</h3>
              <v-alert type="info" variant="tonal">
                <div class="d-flex justify-space-between align-center">
                  <div>
                    <strong>商品:</strong> {{ searchResult.productName }} ({{ searchResult.productCode }})<br>
                    <strong>时间范围:</strong> {{ formatMonth(searchResult.startDate) }} - {{ formatMonth(searchResult.endDate) }}<br>
                    <strong>查询时间:</strong> {{ new Date().toLocaleString('zh-CN') }}
                  </div>
                  <v-icon size="40">mdi-package-variant</v-icon>
                </div>
              </v-alert>
            </v-card-text>
          </v-card>
          
          <!-- 加载状态提示 -->
          <v-overlay
            v-model="loadingAll"
            class="align-center justify-center"
          >
            <v-progress-circular
              indeterminate
              size="64"
            ></v-progress-circular>
          </v-overlay>
        </v-container>
      </v-main>
    </v-app>
  </div>

  <script>
    const { createApp } = Vue
    
    const app = createApp({
      data() {
        return {
          // 时间选择
          startDate: null,
          endDate: null,
          
          // 产品选择
          selectedProduct: null,
          
          // 可用的月份选项
          availableMonths: [],
          
          // 可用的产品选项
          availableProducts: [],
          
          // 加载状态
          loadingStart: false,
          loadingEnd: false,
          loadingProducts: false,
          loadingAll: false,
          searching: false,
          
          // 查询结果
          searchResult: null,
          
          // 缓存数据
          monthsCache: [],
          productsCache: {} // 按时间范围缓存产品数据
        }
      },
      
      computed: {
        // 结束时间验证规则
        endDateRule() {
          return (value) => {
            if (!value) return true
            if (!this.startDate) return '请先选择开始时间'
            if (value < this.startDate) return '结束时间不能早于开始时间'
            return true
          }
        }
      },
      
      methods: {
        // 页面挂载时获取月份数据
        async mounted() {
          await this.loadAvailableMonths();
        },
        
        // 加载可用月份
        async loadAvailableMonths() {
          this.loadingAll = true;
          try {
            // 模拟 API 调用
            // const response = await fetch('/api/available-months/');
            // const data = await response.json();
            
            // 模拟数据 - 实际项目中替换为真实 API 调用
            const mockData = await this.mockApiCall('/api/available-months/');
            
            // 转换数据格式
            this.availableMonths = mockData.map(month => ({
              value: month,
              text: this.formatMonth(month)
            }));
            
            // 缓存原始数据
            this.monthsCache = mockData;
            
          } catch (error) {
            console.error('加载月份数据失败:', error);
            this.showSnackbar('加载月份数据失败', 'error');
            
            // 提供默认数据作为备用
            this.availableMonths = this.generateDefaultMonths();
          } finally {
            this.loadingAll = false;
          }
        },
        
        // 加载指定时间范围内的产品
        async loadProductsInRange() {
          if (!this.startDate || !this.endDate) {
            this.availableProducts = [];
            return;
          }
          
          // 检查缓存
          const cacheKey = `${this.startDate}-${this.endDate}`;
          if (this.productsCache[cacheKey]) {
            this.availableProducts = this.productsCache[cacheKey];
            return;
          }
          
          this.loadingProducts = true;
          try {
            // 模拟 API 调用
            // const response = await fetch(`/api/products/?start=${this.startDate}&end=${this.endDate}`);
            // const data = await response.json();
            
            // 模拟数据 - 实际项目中替换为真实 API 调用
            const mockData = await this.mockApiCall(`/api/products/?start=${this.startDate}&end=${this.endDate}`);
            
            // 转换数据格式
            this.availableProducts = mockData.map(product => ({
              code: product.code,
              name: product.name,
              category: product.category || '未分类'
            }));
            
            // 缓存数据
            this.productsCache[cacheKey] = this.availableProducts;
            
          } catch (error) {
            console.error('加载产品数据失败:', error);
            this.showSnackbar('加载产品数据失败', 'error');
            this.availableProducts = [];
          } finally {
            this.loadingProducts = false;
          }
        },
        
        // 开始时间变化处理
        onStartDateChange(value) {
          this.startDate = value;
          this.resetEndDateAndProduct();
          
          // 如果选择了结束时间，验证时间范围
          if (this.endDate && this.endDate < value) {
            this.endDate = null;
          }
        },
        
        // 结束时间变化处理
        onEndDateChange(value) {
          this.endDate = value;
          if (value) {
            this.loadProductsInRange();
          } else {
            this.availableProducts = [];
            this.selectedProduct = null;
          }
        },
        
        // 重置结束时间和产品选择
        resetEndDateAndProduct() {
          this.endDate = null;
          this.selectedProduct = null;
          this.availableProducts = [];
        },
        
        // 查询产品信息
        async searchProducts() {
          if (!this.startDate || !this.endDate || !this.selectedProduct) {
            this.showSnackbar('请完整选择时间范围和产品', 'warning');
            return;
          }
          
          this.searching = true;
          try {
            // 模拟 API 调用
            // const response = await fetch(`/api/product-info/?product=${this.selectedProduct}&start=${this.startDate}&end=${this.endDate}`);
            // const data = await response.json();
            
            // 模拟数据
            const mockData = await this.mockSearchCall(this.selectedProduct, this.startDate, this.endDate);
            
            this.searchResult = {
              productCode: this.selectedProduct,
              productName: this.availableProducts.find(p => p.code === this.selectedProduct)?.name || '未知产品',
              startDate: this.startDate,
              endDate: this.endDate,
              data: mockData
            };
            
            this.showSnackbar('查询成功', 'success');
            
          } catch (error) {
            console.error('查询失败:', error);
            this.showSnackbar('查询失败', 'error');
          } finally {
            this.searching = false;
          }
        },
        
        // 重置所有选择
        resetSelections() {
          this.startDate = null;
          this.endDate = null;
          this.selectedProduct = null;
          this.availableProducts = [];
          this.searchResult = null;
        },
        
        // 格式化月份显示
        formatMonth(monthStr) {
          if (!monthStr) return '';
          const year = monthStr.substring(0, 4);
          const month = monthStr.substring(4, 6);
          return `${year}年${parseInt(month)}月`;
        },
        
        // 生成默认月份（备用）
        generateDefaultMonths() {
          const months = [];
          const now = new Date();
          const currentYear = now.getFullYear();
          const currentMonth = now.getMonth() + 1;
          
          // 生成过去12个月到未来12个月的数据
          for (let i = -12; i <= 12; i++) {
            const date = new Date(currentYear, currentMonth - 1 + i, 1);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const monthStr = `${year}${month}`;
            
            months.push({
              value: monthStr,
              text: this.formatMonth(monthStr)
            });
          }
          
          return months;
        },
        
        // 模拟 API 调用（实际项目中替换为真实调用）
        async mockApiCall(url) {
          // 模拟网络延迟
          await new Promise(resolve => setTimeout(resolve, 500));
          
          // 模拟月份数据
          if (url.includes('/api/available-months/')) {
            const months = [];
            const startYear = 2024;
            const endYear = 2026;
            
            for (let year = startYear; year <= endYear; year++) {
              for (let month = 1; month <= 12; month++) {
                const monthStr = `${year}${String(month).padStart(2, '0')}`;
                months.push(monthStr);
              }
            }
            return months;
          }
          
          // 模拟产品数据
          if (url.includes('/api/products/')) {
            const products = [
              { code: 'PROD001', name: '笔记本电脑', category: '电子产品' },
              { code: 'PROD002', name: '智能手机', category: '电子产品' },
              { code: 'PROD003', name: '无线耳机', category: '配件' },
              { code: 'PROD004', name: '机械键盘', category: '配件' },
              { code: 'PROD005', name: '显示器', category: '电子产品' }
            ];
            return products;
          }
          
          return [];
        },
        
        // 模拟搜索调用
        async mockSearchCall(productCode, startDate, endDate) {
          await new Promise(resolve => setTimeout(resolve, 300));
          
          return {
            productCode: productCode,
            startDate: startDate,
            endDate: endDate,
            salesData: {
              totalSales: Math.floor(Math.random() * 10000) + 1000,
              averagePrice: (Math.random() * 1000 + 100).toFixed(2),
              stockLevel: Math.floor(Math.random() * 500) + 50
            }
          };
        },
        
        // 显示 Snackbar 提示
        showSnackbar(text, color = 'success') {
          // 这里可以使用实际的 Snackbar 组件
          console.log(`${color}: ${text}`);
        }
      },
      
      mounted() {
        // 初始化 Vuetify
        const vuetify = Vuetify.createVuetify({
          theme: {
            defaultTheme: 'light'
          }
        });
        
        this.$nextTick(() => {
          app.use(vuetify);
        });
      }
    });
    
    app.mount('#app');
  </script>
</body>
</html>